# -*- coding: utf-8 -*-

import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanLuzhouPolicy(BaseTaxPolicySpider):
    name = 'sichuan_luzhou_qu_policy'

    province = '四川省'
    city = '泸州市'
    # county = '滑县'
    park = ''

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                "CONCURRENT_REQUESTS": 2,
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": None,
                # },
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['泸州市江阳区人民政府', "江阳区", "https://www.jiangyang.gov.cn/zwgk/zc/gfxwj2"],
            ['泸州市江阳区人民政府', "江阳区", "https://www.jiangyang.gov.cn/zwgk/zc/zfwj/wj"],
            ['泸州市纳溪区人民政府', "纳溪区", "https://www.naxi.gov.cn/zw/zc/gfxwj"],
            ['泸州市纳溪区人民政府', "纳溪区", "https://www.naxi.gov.cn/zw/zc/zfwj/zcwj"],
            ['泸州市龙马潭区人民政府', "龙马潭区", "https://www.longmatan.gov.cn/zw/zc/gfxwj"],
            ['泸州市龙马潭区人民政府', "龙马潭区", "https://www.longmatan.gov.cn/zw/zc/zfwj1/zfwj"],
            ['泸州市泸县人民政府', "泸县", "https://www.luxian.gov.cn/zwgk/zc/gfxwj"],
            ['泸州市泸县人民政府', "泸县", "https://www.luxian.gov.cn/zwgk/zc/zfwj1/zfwj"],
            ['泸州市合江县人民政府', "合江县", "https://www.hejiang.gov.cn/gk/zc/gfxwj2"],
            ['泸州市合江县人民政府', "合江县", "https://www.hejiang.gov.cn/gk/zc/zfwj22/zfwj"],
            ['泸州市叙永县人民政府', "叙永县", "https://www.xuyong.gov.cn/zwgk/zc/gfxwj"],
            ['泸州市叙永县人民政府', "叙永县", "https://www.xuyong.gov.cn/zwgk/zc/zfwj"],
            ['泸州市古蔺县人民政府', "古蔺县", "https://www.gulin.gov.cn/zwgk/zc/gfxwj"],
            ['泸州市古蔺县人民政府', "古蔺县", "https://www.gulin.gov.cn/zwgk/zc/zcfg/zfwj"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        if ('在 2 秒后执行下一个请求' in response.text or '搜索过于频繁，请输入验证码' in response.text) and not response.xpath("//*[@class='first']") and meta.get('retry_time', 0) < 10:
            meta['retry_time'] = meta.get('retry_time', 0) + 1
            # print(response.text)
            print('retry_time', meta['retry_time'], response.url)
            time.sleep(3)
            yield response.follow(response.url, callback=self.parse_list, meta=meta, dont_filter=True)
            return
        elem_list = response.xpath(
            "//ul//li//a[(contains(@href, 'content_') and @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=5] | "
            "//tr//a[(contains(@href, 'content_') and @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9]"
        )

        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a[@title]/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath(""".//*[@class='date']/text()""").getall()[-1]
            if item['publish_date'] < '2022-01-01':
                # self.get_next = None
                pass
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if self.get_next or self.get_next == '0':
            page = response.meta.get('page', 1)
            next_url = response.xpath(
                """//a[text()='下页' or ./text()='下页>' or text()='»' or contains(./text(), '下一页') or text()='下一页»']/@href""").get()
            if not next_url:
                next_url = response.xpath(f"""//b[text()='{page}']/following::a/@href""").get()
            if next_url and next_url not in ['javascript:void(0);'] and response.urljoin(next_url) != response.url:
                print(response.url, 'next', next_url)
                yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item, "page": page + 1})
            else:
                # print(response.text)
                print(response.url, 'not next_url')

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get() or response.xpath("/title/text()").get()
        # item['publish_date'] = response.xpath("//span[contains(.//text(), '发布时间')]/following-sibling::span//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_luzhou_qu_policy -a get_next=1".split())
